package com.octopus.yangj.customized.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.octopus.kernal.controller.AbstractCustomizedController;
import com.octopus.kernal.ui.builder.DetailTableBuilder;
import com.octopus.kernal.ui.builder.QueryTableBuilder;
import com.octopus.kernal.ui.builder.SearchTableBuilder;
import com.octopus.yangj.customized.service.LogService;
import com.octopus.yangj.generated.controller.KnowledgeValidator;
import com.octopus.yangj.generated.controller.SearchKnowledgeCommand;
import com.octopus.yangj.generated.model.KnowledgeStruct;
import com.octopus.yangj.generated.service.KnowledgeService;
import com.wushi.yangjing.ExcelMgt;

@Controller
@RequestMapping("/knowledge/x")
public class CustomizedKnowledgeController extends AbstractCustomizedController<KnowledgeStruct, SearchKnowledgeCommand, Long>{

    @Autowired
    private LogService logService;
    
    @Autowired
    private KnowledgeService knowledgeService;
    
    @Autowired
    private QueryTableBuilder<KnowledgeStruct> queryTableBuilder;
    
    @Autowired
    private SearchTableBuilder<KnowledgeStruct> searchTableBuilder;
    
    @Autowired
    private DetailTableBuilder<KnowledgeStruct> detailTableBuilder;
    
    @Autowired
    private KnowledgeValidator knowledgeValidator;
    
    @RequestMapping(value = "/query_embed.o", method = RequestMethod.GET)
    public String back(Model model, HttpServletRequest request, SearchKnowledgeCommand searchCommand){
    	String offset = request.getParameter("pager.offset");
    	if(StringUtils.isBlank(offset))
    		return "redirect:../query.o";
    	else
    		return "redirect:../query.o?pager.offset=" + offset;
    }
    
    @RequestMapping(value = "/query.o", method = RequestMethod.GET)
    public String queryEmbed(Model model, HttpServletRequest request,
        @ModelAttribute
        SearchKnowledgeCommand searchCommand) {
        if (searchCommand == null) {
            searchCommand = new SearchKnowledgeCommand();
        }
        Object knowledgeCommand = request.getSession().getAttribute("knowledgeCommand");
        Object knowledgeCommand2 = request.getSession().getAttribute("knowledgeCommand2");
        Object knowledgeOperator = request.getSession().getAttribute("knowledgeOperator");
        String offset = request.getParameter("pager.offset");
        String psort = request.getParameter("field.sort");
        if (StringUtils.isNotBlank(offset)) {
            searchCommand.setOffset(Integer.parseInt(offset));
            if (knowledgeCommand!= null) {
                searchCommand.setEntity(((KnowledgeStruct) knowledgeCommand));
            }
            if (knowledgeCommand2 != null) {
                searchCommand.setEntity2(((KnowledgeStruct) knowledgeCommand2));
            }
            if (knowledgeOperator!= null) {
                searchCommand.setOperator(((KnowledgeStruct) knowledgeOperator));
            }
        } else {
            request.getSession().setAttribute("knowledgeCommand", null);
            request.getSession().setAttribute("knowledgeCommand2", null);
            request.getSession().setAttribute("knowledgeOperator", null);
            request.getSession().setAttribute("knowledgeSort", null);
        }
        if (StringUtils.isNotBlank(psort)) {
            request.getSession().setAttribute("knowledgeSort", psort);
        }
        Object knowledgeSort = request.getSession().getAttribute("knowledgeSort");
        if (knowledgeSort!= null) {
            searchCommand.setPropertiesSorted(new String[] {knowledgeSort.toString()});
        }
        List<KnowledgeStruct> list = knowledgeService.search(searchCommand);
        request.setAttribute("entities", list);
        request.setAttribute("searchCommand", searchCommand);
        List<String> disabledFields = new ArrayList<String>();
        disabledFields.add("_actions");
        request.setAttribute("knowledgeQueryTable", queryTableBuilder.build(request, "Knowledge", list, ((String) knowledgeSort), disabledFields, null, null, knowledgeValidator.getMessageSource()));
        request.setAttribute("knowledgeSearchTable", searchTableBuilder.build(request, searchCommand, knowledgeValidator.getMessageSource()));
        return "customized/knowledge/query_embed";
    }
    
    @RequestMapping(value = "/query.o", method = RequestMethod.POST)
    public String searchEmbed(Model model, HttpServletRequest request,
        @ModelAttribute
        SearchKnowledgeCommand searchCommand) {
        request.getSession().setAttribute("knowledgeCommand", searchCommand.getEntity());
        request.getSession().setAttribute("knowledgeCommand2", searchCommand.getEntity2());
        request.getSession().setAttribute("knowledgeOperator", searchCommand.getOperator());
        return "redirect:/knowledge/x/query.o?pager.offset=0";
    }
    
    @RequestMapping(value = "/view.o", method = RequestMethod.GET)
    public String viewEmbed(Model model, HttpServletRequest request,
        @RequestParam
        Long id,
        @ModelAttribute
        KnowledgeStruct entity) {
        model.addAttribute("ACTION", "view");
        KnowledgeStruct entity2 = knowledgeService.getEntity(id);
        try {
            BeanUtils.copyProperty(entity, "attributeValues", entity2 .getAttributeValues());
        } catch (Exception _x) {
            _x.printStackTrace();
        }
        request.setAttribute("knowledgeDetailTable", detailTableBuilder.build(request, entity, knowledgeValidator.getMessageSource(), true));
        request.setAttribute("knowledgeDetailButtons", detailTableBuilder.buildButton(request, entity, knowledgeValidator.getMessageSource(), true, false));
        return "customized/knowledge/edit_embed";
    }
    
    @RequestMapping(value = "/export.o")
    public void exportKnowledge(Model model, HttpServletRequest request, HttpServletResponse response,
            @RequestParam
            Long id,
            @ModelAttribute
            SearchKnowledgeCommand searchCommand) {
    	KnowledgeStruct knowledge = knowledgeService.getEntity(id);
		List<KnowledgeStruct> list = new ArrayList<KnowledgeStruct>();
		list.add(knowledge);
		this.export(list, request, response);
    }
    
    @RequestMapping(value = "/exports.o")
    public void exportKnowledges(Model model, HttpServletRequest request, HttpServletResponse response) {
    	SearchKnowledgeCommand searchCommand = new SearchKnowledgeCommand();
    	searchCommand.setMaxPageItems(Integer.MAX_VALUE);
        Object knowledgeCommand = request.getSession().getAttribute("knowledgeCommand");
        Object knowledgeCommand2 = request.getSession().getAttribute("knowledgeCommand2");
        Object knowledgeOperator = request.getSession().getAttribute("knowledgeOperator");
        if (knowledgeCommand!= null) {
            searchCommand.setEntity(((KnowledgeStruct) knowledgeCommand));
        }
        if (knowledgeCommand2 != null) {
            searchCommand.setEntity2(((KnowledgeStruct) knowledgeCommand2));
        }
        if (knowledgeOperator!= null) {
            searchCommand.setOperator(((KnowledgeStruct) knowledgeOperator));
        }
		List<KnowledgeStruct> list = knowledgeService.search(searchCommand);
		this.export(list, request, response);
    }
    
    private void export(List<KnowledgeStruct> list, HttpServletRequest request, HttpServletResponse response){
		String path = request.getSession().getServletContext().getRealPath("/WEB-INF/knowledgeTemplate.xls");
		File template=new File(path);
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition","attachment; filename=datasheet.xls");
			ExcelMgt.getInstance().exportExcel(list, template, out);
	    	logService.log("knowledge", "export", null);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
	
}
